package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lixu
 */
@Service
public class DtsPermissionServiceImpl implements DtsPermissionService {
    @Autowired
    private DtsPermissionMapper dtsPermissionMapper;
    /**
     * 根据角色IDS 查询权限 集合
     * @param roleIds
     * @return
     */
    @Override
    public Set<String> findDtsPermsPermissionByRoleIds(Integer[] roleIds) {
        //select permission from dts_perm where role_id in (1,2,3)
        LambdaQueryWrapper<DtsPermission> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(DtsPermission::getPermission) //查询指定字段
                          .in(DtsPermission::getRoleId,roleIds)
                          .eq(DtsPermission::getDeleted,false);//启用状态
        List<DtsPermission> dtsPermissionList = dtsPermissionMapper.selectList(lambdaQueryWrapper);
        return dtsPermissionList.stream().map(DtsPermission::getPermission).collect(Collectors.toSet());
    }

    /**根据角色ID 查询权限 集合
     *
     * @param roleId
     * @return
     */
    @Override
    public Set<String> findDtsPermsPermissionByRoleId(Integer roleId) {
        //select permission from dts_perm where role_id = 2
        LambdaQueryWrapper<DtsPermission> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(DtsPermission::getPermission) //查询指定字段
                .eq(DtsPermission::getRoleId,roleId)
                .eq(DtsPermission::getDeleted,false);//启用状态
        List<DtsPermission> dtsPermissionList = dtsPermissionMapper.selectList(lambdaQueryWrapper);
        return dtsPermissionList.stream().map(DtsPermission::getPermission).collect(Collectors.toSet());
    }

    /**
     * 根据角色ID 修改权限
     * @param permissions
     * @param roleId
     */
    @Override
    public void updatePermissionsByRoleId(List<String> permissions, Integer roleId) {
        // select * from dts_permission where ....
        // update dts_permission set delete = 1 where role_id = ?
        //1:删除
        DtsPermission dtsPermission = new DtsPermission();
        dtsPermission.setDeleted(true);//未启动  （逻辑删除）
        dtsPermissionMapper.update(dtsPermission,new QueryWrapper<DtsPermission>()
           .eq("role_id",roleId));
        //2:批量添加  insert into 表 ()  values (),(),(),()  Mp
        dtsPermissionMapper.insertDtsPermissionByRoleId(permissions,roleId,new Date(),0);

    }
}
